package com.qianfeng.goods.service;

import java.util.List;

import com.qianfeng.goods.bean.Cart;
import com.qianfeng.goods.mapper.CartMapper;
import com.qianfeng.utils.DBUtils;

public class CartService {

	/**
	 * 根据购物车id和用户id更新商品数量
	 * 
	 * @param cart
	 * @return
	 */
	public boolean updateCartByIdAndUserId(Cart cart) {
		CartMapper cartMapper = DBUtils.getMapper(CartMapper.class);
		int num = cartMapper.updateCartByIdAndUserId(cart);
		DBUtils.release();
		return num > 0;
	}

	/**
	 * 获取购物车中的所有商品
	 * 
	 * @param cart
	 * @return
	 */
	public List<Cart> getList(Cart cart) {
		CartMapper cartMapper = DBUtils.getMapper(CartMapper.class);
		List<Cart> list = cartMapper.getList(cart);
		DBUtils.release();
		return list;
	}

	/**
	 * 加入购物车
	 * 
	 * @param cart
	 * @return
	 */
	public boolean addToCart(Cart cart) {
		CartMapper cartMapper = DBUtils.getMapper(CartMapper.class);
		Cart cart2 = cartMapper.getCartByGoodsIdAndUserId(cart);
		int i = 0;
		if (cart2 != null) {

			int num = cart2.getNum();
			if (num > 0) {
				cart.setNum(cart.getNum() + num);
				i = cartMapper.updateCart(cart);

			}

		} else {
			cart.setCreate_time(System.currentTimeMillis());
			i = cartMapper.saveCart(cart);
		}
		DBUtils.release();
		return i > 0;
	}

	/**
	 * 根据购物车id和用户id删除购物车记录
	 * 
	 * @param cart
	 * @return
	 */
	public boolean deleteByIdAndUserId(Cart cart) {
		CartMapper cartMapper = DBUtils.getMapper(CartMapper.class);
		int num = cartMapper.deleteCartByGoodsIdAndUserId(cart);
		DBUtils.release();
		return num > 0;
	}

	// 获取提交订单时选中的商品
	public List<Cart> getGoodsByCartId(Cart cart) {
		CartMapper cartMapper = DBUtils.getMapper(CartMapper.class);
		List<Cart> list = cartMapper.getGoodsByCartId(cart);
		DBUtils.release();
		return list;
	}
}
